<template>
	<div class="app-container">
		<div ref="box1">
			<div class="flex-center" style="">
				<jk-search-input v-model="searchParams.customerName" style="width: 240px;" placeholder="客户" size="large" class="item-gap" clearable @on-enter="onSearchBtn" />
				<jk-search-input v-model="searchParams.productName" style="width: 240px;" placeholder="品种名称" size="large" class="item-gap" clearable @on-enter="onSearchBtn" />
				<jk-search-button size="large" @click="onSearchBtn"></jk-search-button>
			</div>
			<jk-divider-card title="筛选栏" icon="el-icon-search" placement="center" class="margin-bottom-10 margin-top-20">
				<el-row class="search-box" :gutter="14">
					<el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
						<div class="search-item" style="border-top: solid 1px #eee;">
							<div class="search-item-label"><span class="el-icon-location-information item-gap"></span> 销售地区:</div>
							<div class="search-item-val">
								<el-radio-group v-model="searchParams.areaId" size="mini">
									<el-radio-button v-for="(areaItem, areaIndex) in areaList" :key="areaIndex" :label="areaItem.id">{{ areaItem.name }}</el-radio-button>
								</el-radio-group>
							</div>
						</div>
					</el-col>
					<el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
						<div class="search-item" style="border-top: solid 1px #eee;">
							<div class="search-item-label"><span class="el-icon-coin item-gap"></span> 小计成本:</div>
							<div class="search-item-val">
								<el-radio-group v-if="!showCustomSubTotal" v-model="sortFieldConfig.subTotal" size="mini" @change="onRatioChange($event, 'subTotal')">
									<el-radio-button :label="1">由低到高</el-radio-button>
									<el-radio-button :label="2">由高到低</el-radio-button>
								</el-radio-group>
								<div v-else class="flex-start-center">
									<jk-number-input v-model="searchParams.subTotalMin" size="mini" placeholder="起"></jk-number-input>
									<span>-</span>
									<jk-number-input v-model="searchParams.subTotalMax" size="mini" placeholder="止"></jk-number-input>
								</div>
								<el-button size="mini" @click="showCustomSubTotal = !showCustomSubTotal">{{ showCustomSubTotal ? '收起' : '自定义' }}</el-button>
							</div>
						</div>
					</el-col>
					<el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
						<div class="search-item">
							<div class="search-item-label"><span class="el-icon-date item-gap"></span> 报价日期:</div>
							<div class="search-item-val">
								<el-radio-group v-if="!showCustomBelongDate" v-model="sortFieldConfig.belongDate" size="mini" @change="onRatioChange($event, 'belongDate')">
									<el-radio-button :label="1">由近到远</el-radio-button>
									<el-radio-button :label="2">由远到近</el-radio-button>
								</el-radio-group>
								<div v-else class="flex-start-center">
									<jk-date-picker v-model="searchParams.belongDateMin" type="date" size="mini" placeholder="起"></jk-date-picker>
									<span>-</span>
									<jk-date-picker v-model="searchParams.belongDateMax" type="date" size="mini" placeholder="止"></jk-date-picker>
								</div>
								<el-button size="mini" @click="showCustomBelongDate = !showCustomBelongDate">{{ showCustomBelongDate ? '收起' : '自定义' }}</el-button>
							</div>
						</div>
					</el-col>
					<el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
						<div class="search-item">
							<div class="search-item-label"><div class="item-gap" style="width: 12px;text-align: center;">¥</div>报价金额:</div>
							<div class="search-item-val">
								<el-radio-group v-if="!showCustomOfferPrice" v-model="sortFieldConfig.offerPrice" size="mini" @change="onRatioChange($event, 'offerPrice')">
									<el-radio-button :label="1">由低到高</el-radio-button>
									<el-radio-button :label="2">由高到低</el-radio-button>
								</el-radio-group>
								<div v-else class="flex-start-center">
									<jk-number-input v-model="searchParams.offerPriceMin" size="mini" placeholder="起"></jk-number-input>
									<span>-</span>
									<jk-number-input v-model="searchParams.offerPriceMax" size="mini" placeholder="止"></jk-number-input>
								</div>
								<el-button size="mini" @click="showCustomOfferPrice = !showCustomOfferPrice">{{ showCustomOfferPrice ? '收起' : '自定义' }}</el-button>
							</div>
						</div>
					</el-col>
					<el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
						<div class="search-item">
							<div class="search-item-label"><span class="el-icon-tickets item-gap"></span> 品种支数:</div>
							<div class="search-item-val">
								<el-radio-group v-if="!showCustomYarnCount" v-model="sortFieldConfig.yarnCount" size="mini" @change="onRatioChange($event, 'yarnCount')">
									<el-radio-button :label="1">由多到少</el-radio-button>
									<el-radio-button :label="2">由少到多</el-radio-button>
								</el-radio-group>
								<div v-else class="flex-start-center">
									<jk-number-input v-model="searchParams.yarnCountMin" size="mini" placeholder="起"></jk-number-input>
									<span>-</span>
									<jk-number-input v-model="searchParams.yarnCountMax" size="mini" placeholder="止"></jk-number-input>
								</div>
								<el-button size="mini" @click="showCustomYarnCount = !showCustomYarnCount">{{ showCustomYarnCount ? '收起' : '自定义' }}</el-button>
							</div>
						</div>
					</el-col>
					<el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
						<div class="search-item">
							<div class="search-item-label"><span class="el-icon-money item-gap"></span> 销售利润:</div>
							<div class="search-item-val">
								<el-radio-group v-if="!showCustomProfit" v-model="sortFieldConfig.profit" size="mini" @change="onRatioChange($event, 'profit')">
									<el-radio-button :label="1">由低到高</el-radio-button>
									<el-radio-button :label="2">由高到低</el-radio-button>
								</el-radio-group>
								<div v-else class="flex-start-center">
									<jk-number-input v-model="searchParams.profitMin" size="mini" placeholder="起"></jk-number-input>
									<span>-</span>
									<jk-number-input v-model="searchParams.profitMax" size="mini" placeholder="止"></jk-number-input>
								</div>
								<el-button size="mini" @click="showCustomProfit = !showCustomProfit">{{ showCustomProfit ? '收起' : '自定义' }}</el-button>
							</div>
						</div>
					</el-col>
				</el-row>
			</jk-divider-card>
		</div>
		<jk-card>
			<jk-table class="hj-table" :span-method="mergeColMethod" :cell-class-name="headerCellClassName" :header-cell-class-name="headerCellClassName" :loading="tableLoading" :data="tableData" :height="tableHeight + 20">
				<vxe-table-column field="productName" title="品种" fixed="left" width="180" align="left"></vxe-table-column>
				<vxe-table-column field="yarnCount" title="支数" width="70" align="right" />
				<vxe-table-column field="customerName" title="客户" width="170" align="left" />
				<vxe-colgroup title="一体丝" field="yts" align="center">
					<template slot="header">
						<span style="font-size: 14px">一体丝</span>
					</template>
					<vxe-table-column field="coreProductName" title="品名" width="140" align="left" />
					<vxe-table-column field="coreContentPrice" title="芯单价(当前)" width="110" align="center" />
					<vxe-table-column field="coreContentNewPrice" title="芯单价(最新)" width="110" align="center" />
					<vxe-table-column field="coreContent" title="含芯" width="70" align="center" />
					<vxe-table-column field="coreContentAmount" title="金额" width="70" align="center" />
				</vxe-colgroup>
				<vxe-colgroup title="氨纶" field="al" align="center">
					<template slot="header">
						<span style="font-size: 14px">氨纶</span>
					</template>
					<vxe-table-column field="spandexProductName" title="品名" width="140" align="left" />
					<vxe-table-column field="spandexQs" title="牵伸" width="70" align="center" />
					<vxe-table-column field="spandexContent" title="氨含" width="70" align="center" />
					<vxe-table-column field="spandexPrice" title="氨价(当前)" width="110" align="center" />
					<vxe-table-column field="spandexNewPrice" title="氨价(最新)" width="110" align="center" />
					<vxe-table-column field="spandexAmount" title="金额" width="70" align="center" />
				</vxe-colgroup>
				<vxe-colgroup title="粗纱" field="cs" align="center">
					<template slot="header">
						<span style="font-size: 14px">粗纱</span>
					</template>
					<vxe-table-column field="csProductName" title="原料" width="140" align="left" />
					<vxe-table-column field="proportion" title="比例" width="70" align="center" />
					<vxe-table-column field="price" title="单价(当前)" width="110" align="center" />
					<vxe-table-column field="newPrice" title="单价(最新)" width="110" align="center" />
					<vxe-table-column field="loss" title="损耗" width="70" align="center" />
					<vxe-table-column field="rawMaterialPrice" title="原料总价" width="70" align="center" />
				</vxe-colgroup>
				<vxe-table-column field="coarseSandCost" title="粗纱" width="70" align="right" />
				<vxe-table-column field="surchargeAmount" title="纺工" width="70" align="right" />
				<vxe-table-column field="coarseSandHc" title="含粗" width="70" align="right" />
				<vxe-table-column field="coarseSandAmount" title="含粗额" width="70" align="right" />
				<vxe-table-column field="subTotal" title="小计" width="70" align="right" />
				<vxe-table-column field="profit" title="利润" width="70" align="right" />
				<vxe-table-column field="offerPrice" title="报价" fixed="right" width="80" align="right" />
				<vxe-table-column field="effectiveStartDate" title="有效期" width="300" align="left">
					<template slot-scope="scope">
						<div>{{ `${scope.row.effectiveStartDate}~${scope.row.effectiveEndDate}` }}</div>
					</template>
				</vxe-table-column>
				<vxe-table-column field="empName" title="报价员" width="70" />
				<vxe-table-column field="belongDate" title="日期" width="110" align="left" />
				<vxe-table-column field="effectiveStartDate" title="状态" width="100" align="center">
					<template slot-scope="scope">
						<el-tag :type="scope.row.state ? 'primary' : 'danger'" size="mini">{{ scope.row.state ? '有效' : '失效' }}</el-tag>
					</template>
				</vxe-table-column>
				<!--<vxe-table-column field="creatorName" title="创建人" width="100" />
				<vxe-table-column field="createTime" title="创建时间" width="150" />
				<vxe-table-column field="updaterName" title="修改人" width="100" />
				<vxe-table-column field="updateTime" title="修改时间" width="150" />-->
				<vxe-column title="操作" field="operation" align="center" fixed="right" :width="100">
					<template slot-scope="scope">
						<div>
							<el-button size="mini" type="primary" icon="el-icon-magic-stick" @click="onEditBtn(scope.row)">选择</el-button>
						</div>
					</template>
				</vxe-column>
			</jk-table>

			<!-- 分页组件 -->
			<footer ref="box2" class="flex-end-center margin-top-10">
				<jk-page
					:page-index="searchParams.pageNo"
					:page-sizes="searchParams.pageSizes"
					:page-size="searchParams.pageSize"
					:total="totalCount"
					@on-change="onPageChange"
				/>
			</footer>
		</jk-card>
	</div>
</template>

<script>
    import calHeight from '/src/mixins/cal-table-height';
    import { pageConfig } from '/src/utils/jk/jk-tool';
    import { auditStateList } from '../../../utils/jk/status-option-list';
    import getMenuColumn from '../../../mixins/getMenuColumn';
    import handlerCache from '../../../mixins/handler-cache';
    import { quotationNuclearPriceRecordPage } from '../../../api/price/customerQuotation';
    import { systemAreaPage } from '../../../api/price/areaConfig';

    export default {
        name: 'CustomerQuotationRecord',
        mixins: [calHeight, getMenuColumn, handlerCache],
        data() {
            return {
                apiItem: {
                    'page': quotationNuclearPriceRecordPage
                },
                prefix: 'quotation:nuclearPriceRecord',
                areaList: [],
                showCustomSubTotal: false,
                showCustomBelongDate: false,
                showCustomOfferPrice: false,
                showCustomYarnCount: false,
                showCustomProfit: false,
                auditStateList: auditStateList,
                dataId: null,
                tableLoading: true,
                exportLoading: false,
                tableData: [],
                totalCount: 0,
                searchParams: {
                    code: '',
                    pageNo: pageConfig.pageNo,
                    pageSize: pageConfig.pageSize,
                    customerName: '',
                    productName: '',
                    auditState: 1,
                    areaId: null,
                    sortParamsList: [],
                    subTotalMin: null,
                    subTotalMax: null,
                    profitMin: null,
                    profitMax: null,
                    yarnCountMin: null,
                    yarnCountMax: null,
                    offerPriceMin: null,
                    offerPriceMax: null,
                    belongDateMin: null,
                    belongDateMax: null
                },
                sortFieldConfig: {
                    belongDate: 1,
                    yarnCount: 1,
                    subTotal: 1,
                    offerPrice: 1,
                    profit: 1
                },
                lastClickSortKey: ''
            };
        },
        mounted() {
            this.getDependentData();
        },
        methods: {
            onRatioChange(e, type) {
                console.log(type);
                this.lastClickSortKey = type;
            },
            onEditBtn(row) {
                this.dataId = row.id;
                this.$toOtherRouter({
                    name: 'addCustomerQuotation',
                    query: {
                        id: row.id,
                        isCopy: '1'
                    }
                });
            },
            mergeColMethod({ row, _rowIndex, column, visibleData }) {
                const prevRow = visibleData[_rowIndex - 1];
                const nextRow = visibleData[_rowIndex + 1];
                const mergeFieldList = ['belongDate', 'productName', 'yarnCount', 'customerName', 'offerPrice', 'subTotal', 'empName', 'creatorName', 'createTime', 'updaterName', 'profit', 'updateTime', 'operation'];
                if (mergeFieldList.includes(column.property)) {
                    return this.mergeFn(prevRow, row, nextRow, column, visibleData, _rowIndex);
                }
            },
            mergeFn(prevRow, row, nextRow, column, visibleData, _rowIndex) {
                if (prevRow && prevRow.id === row.id && prevRow[column.property] === row[column.property]) {
                    return { rowspan: 0, colspan: 0 };
                } else {
                    let countRowspan = 1;
                    while (nextRow && nextRow.id === row.id && nextRow[column.property] === row[column.property]) {
                        nextRow = visibleData[++countRowspan + _rowIndex];
                    }
                    if (countRowspan > 1) {
                        return { rowspan: countRowspan, colspan: 1 };
                    }
                }
            },
            headerCellClassName({ column }) {
                if (['yts', 'coreProductName', 'coreContentPrice', 'coreContentNewPrice', 'coreContent', 'coreContentAmount'].includes(column.field)) {
                    return 'yts-style';
                }
                if (['al', 'spandexProductName', 'spandexQs', 'spandexContent', 'spandexPrice', 'spandexNewPrice', 'spandexAmount'].includes(column.field)) {
                    return 'al-style';
                }
                if (['cs', 'csProductName', 'proportion', 'price', 'loss', 'newPrice', 'rawMaterialPrice'].includes(column.field)) {
                    return 'cs-style';
                }
                return 'default-style';
            },
            onSearchBtn() {
                this.$set(this.searchParams, 'pageNo', 1);
                this.getListRequest();
            },
            onPageChange(e, size) {
                this.$set(this.searchParams, 'pageNo', e);
                this.$set(this.searchParams, 'pageSize', size);
                this.getListRequest();
            },
            clearCacheMethod() {
                // Object.assign(this.$data, this.$options.data());
                this.$nextTick(() => {
                    this.getDependentData();
                });
            },
            getAreaListRequest() {
                return systemAreaPage({ auditState: 1 }).then(res => {
                    if (res.data.status === 200) {
                        this.areaList = res.data.res || [];
                        this.areaList.unshift({
                            id: null,
                            name: '全部'
                        });
                    }
                });
            },
            async getDependentData() {
                this.tableLoading = true;
                await this.getAreaListRequest();
                await this.getListRequest();
                this.tableLoading = false;
            },
            onDetailBtn(row) {
                this.dataId = row.id;
                this.$toOtherRouter({
                    name: 'detailCustomerQuotation',
                    query: {
                        id: row.id
                    }
                });
            },
            /** 查询列表 */
            getListRequest() {
                this.tableLoading = true;
                const params = JSON.parse(JSON.stringify(this.searchParams));
                params.sortParamsList = [];
                // 处理升降序的字段
                for (const key in this.sortFieldConfig) {
                    params.sortParamsList.push({
                        'fieldName': key,
                        'sortType': this.sortFieldConfig[key] // 1-ASC 2-DESC
                    });
                }
                // 最后一次点击的排序字段放在首位
                if (this.lastClickSortKey) {
                    const lastVal = params.sortParamsList.find(x => x.fieldName === this.lastClickSortKey).sortType;
                    params.sortParamsList = params.sortParamsList.filter(x => x.fieldName !== this.lastClickSortKey);
                    params.sortParamsList.unshift({
                        'fieldName': this.lastClickSortKey,
                        'sortType': lastVal
                    });
                }
                return this.apiItem['page'](params).then(res => {
                    this.tableLoading = false;
                    if (res.data.status === 200) {
                        const resData = res.data.res ? JSON.parse(JSON.stringify(res.data.res)) : [];
                        const arr = [];
                        resData.forEach(x => {
                            x.coarseSandItemList.forEach(k => {
                                arr.push({
                                    ...x,
                                    'csProductName': k.productName,
                                    'proportion': k.proportion,
                                    'price': k.price,
                                    'loss': k.loss,
                                    'rawMaterialPrice': k.rawMaterialPrice,
                                    'newPrice': k.newPrice,
                                    state: Date.now() <= Date.parse(x.effectiveEndDate) ? 1 : 0
                                });
                            });
                        });
                        this.tableData = arr;
                        this.totalCount = res.data.count;
                    }
                });
            }
        }
    };
</script>
<style scoped>

</style>

<style scoped lang="scss">
    .hj-table::v-deep .yts-style {
        background-color: #fef0f0;
        //color: #fff;
    }
    .hj-table::v-deep .al-style {
        background-color: #fdf6ec;
        //color: #fff;
    }
    .hj-table::v-deep .cs-style {
        background-color: #ecf5ff;
        //color: #fff;
    }
    .hj-table::v-deep .default-style {
        //background-color: #e8eaec;
        //color: #fff;
    }
    .search-box {
        .search-item {
            height: 36px;
            border: solid 1px #eee;
            border-top: none;
            display: flex;
            align-items: center;
            .search-item-label {
                width: 100px;
                height: 100%;
                padding: 0 6px;
                font-size: 13px;
                color: #515a6e;
                margin-right: 6px;
                white-space: nowrap;
                display: flex;
                align-items: center;
                background: #f8f8f9;
                border-right: solid 1px #eee;
            }
            .search-item-val {
                width: 100%;
                display: flex;
                justify-content: space-between;
                align-items: center;
                padding-right: 6px;
            }
        }
    }

</style>
